package com.charm.restaurant.controller;

import com.charm.restaurant.common.Result;
import com.charm.restaurant.dto.LoginDTO;
import com.charm.restaurant.entity.User;
import com.charm.restaurant.service.UserService;
import com.charm.restaurant.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 用户控制器
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<UserVO> login(@RequestBody LoginDTO loginDTO) {
        log.info("用户登录：{}", loginDTO.getUsername());
        return userService.login(loginDTO);
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<UserVO> register(@RequestBody User user) {
        log.info("用户注册：{}", user.getUsername());
        return userService.register(user);
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/info")
    public Result<UserVO> info() {
        return userService.getUserInfo();
    }

    /**
     * 用户退出登录
     */
    @PostMapping("/logout")
    public Result<String> logout() {
        return Result.success("退出成功");
    }

    /**
     * 修改用户信息
     */
    @PutMapping("/info")
    public Result<UserVO> updateInfo(@RequestBody User user) {
        return userService.updateInfo(user);
    }

    /**
     * 修改密码
     */
    @PutMapping("/password")
    public Result<String> updatePassword(@RequestBody Map<String, String> passwordMap) {
        log.info("修改密码请求");

        String oldPassword = passwordMap.get("oldPassword");
        String newPassword = passwordMap.get("newPassword");

        if (oldPassword == null || newPassword == null) {
            return Result.error("密码参数不能为空");
        }

        return userService.updatePassword(oldPassword, newPassword);
    }
}
